/**
 * Created by 83617 on 2019/1/2.
 */
var mongoose = require('mongoose')
const Schema = mongoose.Schema;
var activitySchema = new mongoose.Schema({
    name: String,
    theSociety: String,
    detail: String,
    societyId:{
        type: Schema.Types.ObjectId,
        ref: 'society'
    },
    meta:{
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
})

activitySchema.pre('save',function(next){
    if(this.isNew){
        this.meta.createAt = this.meta.updateAt = Date.now()
    }else{
        this.meta.updateAt = Date.now()
    }
    next()
})

activitySchema.statics = {
    fetch:function(cb){
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    findBySociety:function(society,cb) {
        return this
            .findOne({society: society})
            .sort('meta.updateAt')
            .exec(cb)
    },
    //aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
    //.aggregate({
    //    $lookup:{
    //        form:'societies',
    //        localField:'societyId',
    //        foreignField:'_id',
    //        as:'full'
    //    }
    //})
    findByAggr:function(cb){
        return this
            .aggregate([
                {$lookup:{
                    from:'societies',
                    localField:'theSociety',
                    foreignField:'name',
                    as:'full'
                }},
                {
                    $unwind: "$full"
                }
            ])
            .sort('meta.updateAt')
            .exec(cb)
    }
}

module.exports = activitySchema